import { Request, Response } from 'express'
import selectLessonService from '../../service/selectLessonService'
import courseService from '../../service/courseService'
import systemFunctionService from '../../service/systemFunctionService'
import selectHistoriesService from '../../service/selectHistoriesService'
import studentService from '../../service/studentService'
import teacherService from '../../service/teacherService'

class SelectLessonController {

  // 创建已选课程（选课）
  async createSelectLesson(req: Request, res: Response) {
    const form = req.body
    // 查询管理选是否开放选课
    const systemRes = await systemFunctionService.findByRoleAndType(2, 'isSelection')
    if (!systemRes.state) return res.gem('注意：暂未开放选课！')

    // 查询该课程是否开放
    const courseRes = await courseService.findById(form.cid)
    if (!courseRes.state) return res.gem('注意：本课程暂未开放！')

    

    // 查询该课程是否已选
    const selectLessonRes = await selectLessonService.findByCidAndStuNum(form.cid, form.stu_num)
    if (selectLessonRes) return res.gem('您已经选择了该课程！')

    // 检查是否还有剩余人数
    if (courseRes.remaining <= 0) return res.gem('该课程选课人数已满！')

    // 保存选课信息
    const saveRes = await selectLessonService.save(form)
    if (!saveRes) return res.gem('选课失败！')

    // 让课程的选课剩余人数 -1 
    await courseService.updateCourseRemaining(form.cid, courseRes.remaining - 1)

    // TODO 将信息保存一份到 选退课历史 中
    const histories = {
      cname: form.cname,
      tname: form.tname,
      lesson_period: form.lesson_period,
      type: form.type,
      location: form.location,
      credit: form.credit,
      stu_num: form.stu_num,
      selectAt: String(Date.now()), // 选课时间
      operation: '选课',
      cid: form.cid // 课程 id
    }
    selectHistoriesService.save(histories)
    res.gsmd(saveRes, '选课成功！')
  }

  // 根据课程名称，教师名称进行模糊查询
  async findByNameKey(req: Request, res: Response) {
    const form = req.body
    let label = '', value = ''
    // 取出label和值（例如：cname 和 ''）
    Object.keys(form).forEach(item => {
      if (item.includes('name')) {
        label = item
        value = form[item]
      }
    })
    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size
    const courses = await selectLessonService.findByNameKey(label, value, skip, page_size, form.stu_num)
    // 根据课程id，查询对应课程中的数据
    for (let i = 0; i < courses.length; i++) {
      const c = await courseService.findById(courses[i].cid)
      const t = await teacherService.findById(courses[i].tid)
      Object.assign(courses[i], {
        cname: c.course_name,
        location: c.location,
        credit: c.credit,
        lesson_period: c.lesson_period,
        type: c.type,
        tname: t.name
      })
    }
    // console.log(courses);
    const count = await selectLessonService.findByNameKeyCount(label, value, form.stu_num)
    if (!courses) res.gem('查无数据！')
    res.gsmdl(count, courses)
  }

  // 删除已选课程（退课）
  async removeSelectLesson(req: Request, res: Response) {
    // const { id, cid, stu_num } = req.params
    const form = req.body
    const removeRes = await selectLessonService.remove(form.id)
    if (removeRes.affected > 0) {
      const courseRes = await courseService.findById(form.cid)
      // 让课程的选课剩余人数 +1 
      await courseService.updateCourseRemaining(form.cid, courseRes.remaining + 1)
      // TODO 将信息保存一份到 选退课历史 中
      const histories = {
        cname: courseRes.course_name,
        tname: courseRes.teacher_name,
        lesson_period: courseRes.lesson_period,
        type: courseRes.type,
        location: courseRes.location,
        credit: courseRes.credit,
        selectAt: String(Date.now()), // 选课时间
        operation: '退课',
        stu_num: form.stu_num,
        cid: form.cid // 课程 id
      }
      selectHistoriesService.save(histories)
      res.gsm('退课成功！')
    } else {
      res.gem('该已选课程已被删除！')
    }
  }

  // 【教师-学生列表】根据学生名称模糊查询，和教师id查询
  async findByTidAndStuName(req: Request, res: Response) {
    const form = req.body
    let label = '', value = ''
    Object.keys(form).forEach(item => {
      if (item.includes('name')) {
        label = item
        value = form[item]
      }
    })

    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size

    const stus = await selectLessonService.findByTidAndStuName(label, value, skip, page_size, form.tid)
    // 获取去重后的学号数组
    const stu_nums = [...new Set(stus.map(item => {
      return item.stu_num
    }))]
    // 根据学号查询对应学生
    const stuList = []
    for (let i = 0; i < stu_nums.length; i++) {
      const stuRes = await studentService.findOneByStu_num(stu_nums[i])
      stuRes.class = stuRes.classes.class_name
      stuRes.major = stuRes.classes.major_name
      stuRes.college = stuRes.classes.college_name
      stuList.push(stuRes)
    }
    // const stuCount = await selectLessonService.findByNameKeyCount(label, value,form.stu_num)
    res.gsmdl(stuList.length, stuList)
  }

  // 【教师-学生列表-查看已选课程】查询学生选择某一教师的所有课程，根据学生学号和教师id查询
  async findAllTeacherCourseWithStu(req: Request, res: Response) {
    const { stu, tid } = req.query
    const findRes = await selectLessonService.findAllTeacherCourseWithStu(stu, tid)
    // 取出课程id
    const cids = findRes.map(item => {
      return item.cid
    })
    // 根据课程id去查询课程
    const courses = []
    for (let i = 0; i < cids.length; i++) {
      const c = await courseService.findById(cids[i])
      courses.push(c)
    }
    res.gsmd(courses)
  }

}

export default new SelectLessonController()